import random
import json
import requests
import time
from random import randint
from sql.conn_sql import Sql
from frame_work.read_config import global_config
from frame_work.logger import Logger
from frame_work.login import AdminLogin
from frame_work.type_file import Source
from frame_work.setting import *
from frame_work.yaml_file import YAML

# logger = Logger(logger = "extra_func").get_logger()
logger = Logger(__name__).get_logger()
yaml = YAML(os.path.join(base_Dir, 'data', 'data.yaml'))


def get_sql_info(statement, params, **kwargs):
    """
    统一sql查询入口
    :param statement: 查询语句
    :param params: 查询参数
    :param kwargs:输出日志信息
    :return:
    """
    sql = Sql()
    try:
        value = sql.exec_query(statement, params)
        logger.debug(kwargs.get("meta").get("info"))
    except Exception as e:
        logger.error("数据查询出错")
        return False
    else:
        return value


def update_sql_info(statement, params, **kwargs):
    """
    统一sql更新入口
    :param statement: 更新语句
    :param params: 更新参数
    :param kwargs:输出日志信息
    :return:
    """
    sql = Sql()
    try:
        sql.exec_update(statement, params)
        logger.debug(kwargs.get("meta").get("info"))
    except Exception as e:
        logger.error("数据更新出错")
        return False


def get_order_url(source, flag=1):
    """
    通过来源返回商品下单地址
    :param source:
    :param flag:区分不同的地址
    :return: order_url
    """
    order_url = ''
    source = Source[source].value
    # 商品来源为淘宝
    if source == 1:
        if flag == 1:
            order_url = global_config.get_order_url("tb_order_url")
        else:
            order_url = global_config.get_order_url("st_package_url")
    # 商品来源为天猫
    elif source == 2:
        if flag == 1:
            order_url = global_config.get_order_url("tm_order_url")
        else:
            order_url = global_config.get_order_url("st_package_url")
    # 商品来源为京东
    elif source == 5:
        if flag == 1:
            order_url = global_config.get_order_url("jd_order_url")
        else:
            order_url = global_config.get_order_url("pingou_jd_url")
    # 商品来源为拼多多
    elif source == 8:
        order_url = global_config.get_order_url("pdd_order_url")
    # 商品来源为淘宝特价版
    elif source == 13:
        order_url = global_config.get_order_url("tb_tj_url")
    # 商品来源为阿里巴巴
    elif source == 12:
        order_url = global_config.get_order_url("albb_order_url")
    # 商品来源为抖音
    elif source == 14:
        order_url = global_config.get_order_url("douyin_url")
    # 商品来源为惊喜
    elif source == 15:
        order_url = global_config.get_order_url("jx_url")
    else:
        order_url = global_config.get_order_url("other_order_url")
    logger.debug('根据来源获取order_url值 => %s ...' % order_url)
    return order_url


def chinese(nums):
    # 随机生成汉字字符
    chinese_str = ''
    for num in range(1, nums + 1):
        head = random.randint(0xb0, 0xf7)
        body = random.randint(0xa1, 0xfe)
        val = f'{head:x}{body:x}'
        str1 = bytes.fromhex(val).decode('gb2312')
        chinese_str += str1
    return chinese_str


def get_user_account_status(uname):
    """
    检查用户账号是否正常(屏蔽、封号、未激活等)
    :param uname:
    :return:
    """
    statement = """SELECT status,is_active from sk_user where uname = %s"""
    params = (uname,)
    value = get_sql_info(statement, params, meta={
        "info": "查询用户状态status"
    })
    status = value[0].get("status")
    is_active = value[0].get("is_active")
    return status, is_active


def change_user_account_status(uname):
    """
    改变用户状态
    :param uname:
    :return:
    """
    try:
        account_status = get_user_account_status(uname)
    except IndexError as e:
        logger.info('没有此人,请查看表中是否有该账号 reason: %s' % e)
        return False
    except Exception:
        logger.debug('未知原因')
        return False
    else:
        status, is_active = account_status
        if is_active == 0:
            logger.debug("%s该账号未激活，需进行手动激活操作" % uname)
            return False
        else:
            from workspace.shikee.chuji.user import User
            if status == 1:
                logger.debug("%s该账号状态正常" % uname)
                return True
            elif status == 2:
                user = User(uname)
                logger.debug("%s该账号已被屏蔽，将进行解除屏蔽操作" % uname)
                status = user.unblock_user()
                return status
            elif status == 3:
                user = User(uname)
                logger.debug("%s该账号已被封号，将进行解除封号操作" % uname)
                status = user.unban_user()
                return status


def get_tb_status(uname):
    """
    检查用户账号是否绑定淘宝号
    :param uname:
    :return:
    """
    statement = """
            SELECT
                u.uid
            FROM
                sk_user u
            LEFT JOIN sk_user_bind_taobao ub ON u.uid = ub.uid
            LEFT JOIN sk_user_bind_taobao_no ubn ON ub.id = ubn.tbid
            WHERE
                u.uname =  %s"""
    params = (uname,)
    # tb_value = sql.exec_query(query_check_tb_statement,tb_params)
    tb_value = get_sql_info(statement, params, meta={
        "info": "检查用户账号是否绑定淘宝号"
    })
    return tb_value


def bind_tb(uname):
    """
    绑定淘宝号
    :param uname:
    :return:
    """
    tb_value = get_tb_status(uname)
    # 已绑定淘宝号，关联查询2条数据
    if len(tb_value) == 2:
        return True
    logger.debug("%s该账号未绑定淘宝号，将进行绑定操作" % uname)
    orderno_suffix = ''.join(map(str, (randint(1, 9) for i in range(4))))
    yaml_data = yaml.get_data('bind_tb')
    yaml_data.get('data').update({
        "uid": tb_value[0].get("uid"),
        "taobao_account": chinese(4),
        "uname": uname,
        "trade1": ''.join([str(randint(0, 9)) for i in range(0, 10)]) + orderno_suffix,
        "trade2": ''.join([str(randint(0, 9)) for i in range(0, 10)]) + orderno_suffix
    })
    # 管理员登录
    admin_login = AdminLogin()
    admin_login.admin_card_login()
    admin_session = admin_login.get_session()
    response = admin_session.post(
        yaml_data.get('url'),
        data=yaml_data.get('data'),
        headers=yaml_data.get('header'))
    if response.status_code == 500:  # 500的话可能是脏数据引起,实际上已经绑定成功了,待后续开发改
        return True
    if response.status_code == 200 and json.loads(response.text).get('success'):
        logger.debug("%s淘宝号绑定成功" % uname)
        return True
    else:
        data = response.get('data')
        logger.debug("%s淘宝号绑定失败，失败原因: %s" % (uname, data))
        return False


def get_user_address(sign, uid):
    """
    app接口获取用户地址
    :param sign:app登录之后返回的身份
    :param uid:
    :return:
    """
    yaml_data = yaml.get_data('user_address')
    url = yaml_data.get('url') + "?uid=" + str(
        uid) + "&sign=" + sign + "&client_type=1&version=" + yaml_data.get_data("app_version")
    response = requests.get(url, headers=yaml_data.get('header')).text
    json_response = json.loads(response)
    return json_response["data"].get("addresses")


def bind_address(sign, uname, uid):
    """
    绑定试客收货地址
    :param sign:
    :param uname:
    :param uid:
    :return:
    """
    yaml_data = yaml.get_data('bind_user_address')
    yaml_data.get('data').update({
        "uid": uid,
        "sign": sign
    })
    response = requests.post(
        yaml_data.get('url'),
        data=yaml_data.get('data'),
        headers=yaml_data.get('header')).text
    json_response = json.loads(response)
    if json_response.get('code') == 'OK':
        logger.debug("%s试客收货地址绑定成功" % uname)
        return True
    else:
        msg = json_response.get('msg')
        logger.debug("%s试客收货地址绑定失败，失败原因: %s" % (uname, msg))
        return False


def get_binded_shop_list(uname, source):
    """
    获取用户绑定店铺
    :param uname:
    :param source:
    :return:
    """
    statement = """SELECT * from sk_shop where uname =%s and source=%s and is_bind=1"""
    params = (uname, source,)
    value = get_sql_info(statement, params, meta={
        "info": "获取商家用户绑定店铺sid"
    })
    return value


def bind_shop(source, uname):
    """
    绑定店铺
    :param source:
    :param uname:
    :return:
    """
    post_data = {}
    order_url = ''
    statement = """SELECT uid from sk_user where uname=%s"""
    params = (uname,)
    value = get_sql_info(statement, params, meta={
        "info": "获取用户id"
    })
    uid = value[0].get("uid")
    if source == '淘宝':
        order_url = global_config.get_order_url("tb_order_url")
        shop_name = "淘宝店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 1,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": "淘宝旺旺" +
            generate_random_nums(4),
            "remark": "111"}
    elif source == '天猫':
        order_url = global_config.get_order_url("tm_order_url")
        shop_name = "天猫店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 2,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == '京东':
        order_url = global_config.get_order_url("jd_order_url")
        shop_name = "京东店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 3,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == '阿里巴巴':
        order_url = global_config.get_order_url("albb_order_url")
        shop_name = "阿里巴巴店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 5,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == '拼多多':
        order_url = global_config.get_order_url("pdd_order_url")
        shop_name = "拼多多店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 7,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == '微店':
        order_url = global_config.get_order_url("wd_order_url")
        shop_name = "微店店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 8,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == '淘特':
        order_url = global_config.get_order_url("tb_tj_url")
        shop_name = "淘宝特价店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 9,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": "淘宝特价旺旺" +
            generate_random_nums(4),
            "remark": "111"}
    elif source == '京喜':
        order_url = global_config.get_order_url("jx_url")
        shop_name = "京喜店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 15,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == '抖音':
        order_url = global_config.get_order_url("douyin_url")
        shop_name = "抖音店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 14,
            "shop_more[source_name][]": '',
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    elif source == "其他":
        order_url = global_config.get_order_url("other_order_url")
        shop_name = "其他店铺" + generate_random_nums(4)
        post_data = {
            "sid": uid,
            "shop_more[source][]": 6,
            "shop_more[source_name][]": "其他",
            "shop_more[url][]": order_url,
            "shop_more[shop_name][]": shop_name,
            "shop_more[account][]": '',
            "remark": "111"}
    post_data.update({"shop_more[url][]": order_url + generate_random_nums(4)})
    # 管理员登录
    admin_login = AdminLogin()
    admin_login.admin_card_login()
    admin_session = admin_login.get_session()
    yaml_data = yaml.get_data('bind_shop')
    yaml_data.get('data').update(post_data)
    response = admin_session.post(
        yaml_data.get('url'),
        data=yaml_data.get('data'),
        headers=yaml_data.get('header')).text
    json_response = json.loads(response)
    status = json_response.get('success')
    if status:
        logger.debug("%s的%s来源店铺绑定成功" % (uname, source))
        return True
    else:
        # data = response.get('data')
        logger.debug("%s的%s来源店铺绑定失败" % (uname, source))
        return False


def check_tid(tid):
    """
    获取活动try表是否有该活动
    :param tid:
    :return:
    """

    statement = """ SELECT tid FROM sk_try where tid =%s"""
    params = (tid,)
    value = get_sql_info(statement, params, meta={
        "info": "查询活动编号tid"
    })
    try:
        tid = value[0].get('tid')
        return tid
    except BaseException:
        logger.debug("没有该活动")
        return


def get_seller_level(uname):
    """
    获取商家级别(区别单期 or vip)
    :param uname:
    :return:
    """
    statement = """SELECT level from sk_user_seller WHERE uname = %s"""
    params = (uname,)
    value = get_sql_info(statement, params, meta={
        "info": "获取商家级别(单期 or vip)"
    })
    return value


def assert_equal(prompt, response, tips):
    if prompt in response:
        logger.info(tips + '执行成功！')
        return True
    else:
        logger.info(tips + '执行失败！')
        return False


def assert_result_dict(res, tips):
    """
    比对响应结果,统一封装
    :param res: 响应值，未经过序列化操作，原始值
    :param tips:带过来的文案 知道是哪个操作
    :return:
    """
    # app pc接口响应值正向
    right_value_dict = {'success': True, 'state': 'success', 'code': 'OK'}
    try:
        # strict=False 不加的话内容含有html标签时序列化报错 去掉强检查
        res_dict = json.loads(res, strict=False)
    except Exception as e:
        logger.info('未知错误,失败原因：%s 响应内容:%s' % (e, res))
    else:
        def get_dict_intersection():
            dict_inter = [{x: y} for x, y in res_dict.items(
            ) if x in right_value_dict and res_dict[x] == right_value_dict[x]]
            return dict_inter
        dict_inter = get_dict_intersection()
        if len(dict_inter) > 0:
            logger.info(tips + '执行成功！')
            return True
        else:
            logger.info(tips + '执行失败！原因：%s' % res_dict)
            return False


def get_str(content, start_str, end_str):
    start_index = content.index(start_str)
    if start_index >= 0:
        start_index += len(start_str)
    end_index = content.index(end_str)
    return content[start_index:end_index]


def generate_random_nums(num):
    """
    生成num个0~9随机数
    :return:
    """
    nums = ''.join([str(randint(0, 9)) for i in range(0, num)])
    return nums


def get_jid(tid, name):
    """
    封装查用户参与JID
    :param tid:
    :param name:
    :return:
    """
    statement = """SELECT * from sk_join where buyer_uname=%s and tid = %s"""
    params = (name, tid,)
    value = get_sql_info(statement, params, meta={
        "info": "查询参与jid"
    })
    return value


def get_now_time():
    # 获取当前时间时分秒
    return time.strftime('%m-%d-%H:%M:%S', time.localtime(time.time()))

if __name__ == '__main__':
    # uname = 'user157'
    # bind_tb('user117')
    # bind_shop('淘宝特价版',"user0637")
    # get_now_time()
    # print(value)
    bind_tb('buser1964')
